package com.comm.update;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * Created by chenxunlin01 on 2017/10/9.
 */

public class UpdateService extends Service implements AppDownloadListener {

    // 启动app下载
    private final static int START_APP_DOWNLOAD = 1001;
    // 正在下载的apk信息
    private DownloadApkInfo downloadApkInfo;
    private UpdateHandler handler = new UpdateHandler(this);
    // 控制app的下载
    private AppDownloadManager appDownloadManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int flag = super.onStartCommand(intent, flags, startId);
        try {
            UpdateInfo updateInfo = (UpdateInfo) intent.getSerializableExtra("updateinfo");
            if (updateInfo == null) {
                return flag;
            }

            // 判断本地是否有已下载好的apk包
            String filePath = Utils.getDownloadFilePath(UpdateService.this, updateInfo.appSize);
            if (checkIdAppDownloaded(updateInfo, filePath)) {
                onAppDownloadComplete(filePath);
                return flag;
            }

            // md5一致则不用重新下载
            if (downloadApkInfo != null && downloadApkInfo.md5.equals(updateInfo.md5)) {
                return flag;
            }

            // 停止之前的下载任务
            if (appDownloadManager != null) {
                appDownloadManager.cancel(true);
            }

            // 发起新的app下载
            downloadApkInfo = createDownloadApkInfo(updateInfo, filePath);
            Message msg = Message.obtain();
            msg.what = START_APP_DOWNLOAD;
            msg.obj = downloadApkInfo;
            handler.sendMessageDelayed(msg, 500);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }

    public void startAppDownload(DownloadApkInfo downloadApkInfo) {
        appDownloadManager = new AppDownloadManager();
        appDownloadManager.start(downloadApkInfo, handler);
    }

    /**
     * 封装DownloadApkInfo对象
     *
     * @param updateInfo
     * @return
     */
    private DownloadApkInfo createDownloadApkInfo(UpdateInfo updateInfo, String filePath) {
        DownloadApkInfo downloadApkInfo = new DownloadApkInfo();
        downloadApkInfo.md5 = updateInfo.md5;
        downloadApkInfo.appSize = updateInfo.appSize;
        downloadApkInfo.downloadUrl = updateInfo.downloadUrl;
        downloadApkInfo.appLocalPath = filePath;
        return downloadApkInfo;
    }

    /**
     * 判断app是否已下载过
     *
     * @param updateInfo
     * @return
     */
    private boolean checkIdAppDownloaded(UpdateInfo updateInfo, String filePath) {
        // 判断本地是否有已下载好的apk包
        String fileMd5 = SecurityUtil.getInstance().getMessageMd5(filePath);
        if (updateInfo.md5.equals(fileMd5)) {
            return true;
        }
        return false;
    }

    @Override
    public void onAppDownloadComplete(String filePath) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
        startActivity(intent);
        downloadApkInfo = null;
    }

    @Override
    public void onAppDownloadFail(String filePath) {
        Utils.delFile(filePath);
        downloadApkInfo = null;
    }

    public static class UpdateHandler extends Handler {

        private WeakReference<UpdateService> serviceWeakReference;

        public UpdateHandler(UpdateService service) {
            this.serviceWeakReference = new WeakReference<UpdateService>(service);
        }

        @Override
        public void handleMessage(Message msg) {
            UpdateService service = serviceWeakReference.get();
            if (service == null) {
                return;
            }
            switch (msg.what) {
                case AppDownloadManager.DOWNLOAD_COMPLETE:
                    service.onAppDownloadComplete((String) msg.obj);
                    break;
                case AppDownloadManager.DOWNLOAD_FAIL:
                    service.onAppDownloadFail((String) msg.obj);
                    break;
                case AppDownloadManager.DOWNLOAD_SPACE_NOT_ENOUGH:
                    service.onAppDownloadFail((String) msg.obj);
                    break;
                case START_APP_DOWNLOAD:
                    service.startAppDownload((DownloadApkInfo) msg.obj);
                    break;
            }
        }
    }


}
